<template>
  <div class="passwd-container card-shadow">
    <div class="pwd">
      <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdFormRule" label-width="110px">
        <el-form-item label="旧密码" prop="oldPasswd">
          <el-input
            clearable
            type="password"
            placeholder="请填写旧密码"
            :maxLength="20"
            v-model="pwdForm.oldPasswd"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认旧密码" prop="confirmOldPasswd">
          <el-input
            clearable
            type="password"
            placeholder="请再次填写旧密码"
            :maxLength="20"
            v-model="pwdForm.confirmOldPasswd"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPasswd">
          <el-input
            clearable
            type="password"
            show-password
            placeholder="请填写新密码"
            :maxLength="20"
            v-model="pwdForm.newPasswd"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toChange(pwdFormRef)">确认修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { changePassword } from '@/api/passwd'
import Cookies from 'js-cookie'

const pwdFormRef = ref<FormInstance>()
const pwdForm = ref({
  oldPasswd: '',
  confirmOldPasswd: '',
  newPasswd: ''
})
const pwdFormRule = reactive<FormRules<typeof pwdForm>>({
  oldPasswd: { required: true, type: 'string', message: '请填写旧密码' },
  confirmOldPasswd: [
    { required: true, type: 'string', message: '请再次填写旧密码' },
    { validator: confirmPasswd, trigger: 'blur' }
  ],
  newPasswd: { required: true, type: 'string', message: '请填写新密码' }
})

function confirmPasswd(rule: any, value: string, callback: Function) {
  if (value !== pwdForm.value.oldPasswd) {
    return callback(new Error('两次输入密码不一致'))
  }
  callback()
}

const router = useRouter()
// 确认修改
function toChange(form: FormInstance | undefined) {
  if (!form) return
  form.validate((vail: boolean) => {
    if (vail) {
      const body = {
        oldPassword: pwdForm.value.oldPasswd,
        confirmPassword: pwdForm.value.confirmOldPasswd,
        newPassword: pwdForm.value.newPasswd
      }
      changePassword(body).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '修改成功, 请重新登陆'
          })
          sessionStorage.setItem('lastPath', window.location.pathname)
          router.push({
            path: '/login'
          })
          Cookies.remove('quicklyToken')
        }
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.passwd-container {
  width: 100%;
  .pwd {
    width: 25%;
    min-width: 300px;
    padding: 40px 24px 24px 24px;
  }
}
</style>
